/**
 * 
 */
package cn.com.xf.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.codec.binary.Base64;
import org.devlib.schmidt.imageinfo.ImageInfo;

/**
 * @author Administrator
 * 
 */
public class ImageUtils {
	public static ImageInfo checkImage(byte[] bytes) {
		InputStream input = null;
		org.devlib.schmidt.imageinfo.ImageInfo imageInfo = new org.devlib.schmidt.imageinfo.ImageInfo();
		input = new ByteArrayInputStream(bytes);
		imageInfo.setInput(input);
		imageInfo.setDetermineImageNumber(true);
		imageInfo.setCollectComments(true);
		if (imageInfo.check()) {
			return imageInfo;
		} else {
			return null;
		}
	}
	
	/**
	 * 功能描述：base64字符串转换成图片
	 *
	 * @since 2016/5/24
	 */
	public static boolean GenerateImage(String imgStr, String photopath, String photoname) {
	    try {
	        if (imgStr == null) {
	            return false;
	        }
	        //Base64解码
	        byte[] b = Base64.decodeBase64(new String(imgStr).getBytes());
	        for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
	        //如果目录不存在，则创建
	        File file = new File(photopath);
	        if (!file.exists()) {
	            file.mkdirs();
	        }
	        //生成图片
	        OutputStream out = new FileOutputStream(photopath + photoname);
	        out.write(b);
	        out.flush();
	        out.close();
	        return true;
	    } catch (Exception e) {	
	    	System.out.println(e.getMessage());
	        return false;
	    }
	}
	
	 public static String GetImageStr(String photopath, String photoname)  
	    {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理  
	        String imgFile = photopath+photoname;//待处理的图片  
	        InputStream in = null;  
	        byte[] data = null;  
	        //读取图片字节数组  
	        try   
	        {  
	            in = new FileInputStream(imgFile);          
	            data = new byte[in.available()];   
	            in.read(data);  
	            in.close();  
	        }   
	        catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	        //对字节数组Base64编码  
	        byte[] en = Base64.encodeBase64(data);  
	        return new String(en);//返回Base64编码过的字节数组字符串  
	    } 
}
